#include <algorithm>
#include <map>

#include "filesystem.hpp"
#include "string_utils.hpp"
#include "unit_type.hpp"
#include "wml_node.hpp"
#include "wml_parser.hpp"
#include "wml_utils.hpp"

namespace {
std::map<std::string, const_unit_type_ptr> cache;
}

const_unit_type_ptr unit_type::get(const std::string& key)
{
	const_unit_type_ptr& entry = cache[key];
	if(entry) {
		return entry;
	}

	unit_type* u = new unit_type(wml::parse_wml(sys::read_file("units/" + key + ".cfg")));
	u->id_ = key;

	entry = const_unit_type_ptr(u);
	return entry;
}

unit_type::unit_type(wml::const_node_ptr node)
  : description_(node->attr("description")),
    texture_(graphics::texture::get(node->attr("image"))),
	movement_(wml::get_int(node, "movement", 10)),
	cost_(wml::get_int(node, "cost", 1))
{
	abilities_ = util::split(node->attr("abilities"));
	ability_build_city_ = has_ability("settle");
}

variant unit_type::get_value(const std::string& key) const
{
	return variant();
}

bool unit_type::has_ability(const std::string& ability) const
{
	return std::find(abilities_.begin(), abilities_.end(), ability) != abilities_.end();
}
